<?php

namespace app\netdisk\controller;

use app\BaseController;

use think\facade\Log;
use think\facade\Cache;

use think\facade\Db;

use app\netdisk\model\{
    UserMiniapp as UserModel,
    ShareInfo as ShareModel,
    QueryLog as LogModel,
};

class Index extends BaseController
{

    ######################################################################################################################
    # 小程序接口
    ######################################################################################################################

    // 获取公告信息
    public function getNoticeInfo()
    {
        // Cache::clear();
        return $this->success(config('know.notice'));
    }

    // 获取轮播图列表
    public function getBannerList()
    {
        return $this->success(config('know.bannerList'));
    }

    // 获取历史查询记录
    public function getQueryLogList()
    {
        $userInfo = $this->request->userInfo;

        return $this->success(LogModel::getHistoryList($userInfo['id']));
    }

    // 删除历史查询记录
    public function delQueryLog()
    {
        $userInfo = $this->request->userInfo;

        $logId = $this->request->param('log_id');

        return $this->success(LogModel::del($userInfo['id'], $logId));
    }

    ######################################################################################################################

    // 验证用户在服务器的登录状态
    public function checkLogin()
    {
        return $this->success("用户已登录");
    }

    // 用户登录
    public function login()
    {
        $code = $this->request->param('code');

        $params = [
            'appid' => config("know.appid"),
            'secret' => config("know.secret"),
            'js_code' => $code,
            'grant_type' => 'authorization_code',
        ];

        $result = $this->httpRequest(config("know.loginApi"), $params);
        $result = json_decode($result, true);

        if (!empty($result) && isset($result['openid']) && isset($result['session_key'])) {
            $data = UserModel::findData(['openid' => $result['openid']]);
            if (!is_null($data)) {
                UserModel::where(['openid' => $result['openid']])->save(['session_key' => $result['session_key']]);
                $token = $this->setToken($data['id']);
                Cache::set($token, array_merge($data->toArray(), ['token' => $token]));
            } else {
                $info = UserModel::create($result);
                $token = $this->setToken($info['id']);
                Cache::set($token, array_merge($info->toArray(), ['token' => $token]));
            }

            return $this->success(['token' => $token]);
        }

        return $this->fail('登录失败');
    }

    // 推送用户信息
    public function pushUserInfo()
    {
        $userInfo = $this->request->userInfo;

        $data = $this->request->param();

        return $this->success(UserModel::where(['id' => $userInfo['id']])->save($data));
    }

    // 验证网盘链接是否存在
    public function isShareLink()
    {
        $data = $this->request->param('disk_link');

        $result = ShareModel::check($data);
        if ($result)
            return $this->success();
        return $this->fail("分享链接不存在");
    }

    // 查询网盘密码
    public function queryShareLink()
    {
        $userInfo = $this->request->userInfo;
        $data = $this->request->param('disk_link');
        
        // 如果查询过，则直接返回密码
        $res = LogModel::checkLog($userInfo['id'], $data);
        if($res){
            return $this->success($res['share_pass']);
        }
        
        // 判断剩余可查询次数
        $hit = LogModel::getHitToday($userInfo['id']);
        if(!$hit){
            return $this->fail("您的今日查询次数已用完");
        }
        
        $result = ShareModel::queryShareLink($data);
        if ($result) {
            $this->queryLog($result);
            return $this->success($result['share_pass']);
        }

        return $this->fail("分享链接不存在");
    }

    // 记录用户查询记录
    private function queryLog($data)
    {
        $userInfo = $this->request->userInfo;
        $linkId = $data['id'];

        unset($data['id']);
        $data['user_id'] = $userInfo['id'] ?? 0;
        $data['nick_name'] = $userInfo['nick_name'] ?? '';
        $data['avatar_url'] = $userInfo['avatar_url'] ?? '';

        // 启动事务
        Db::startTrans();
        try {
            LogModel::create($data);
            ShareModel::incData($linkId);
            UserModel::incData($userInfo['id']);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
    }

    //

}
